"use client";

import React, { useState, useEffect, useRef } from "react";
import { Editor, Toolbar } from "@wangeditor/editor-for-react";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import "@wangeditor/editor/dist/css/style.css";
import "@/styles/wangeditor.css";
import { ossAPI } from "@/lib/api";
import { useMessage } from '@/hooks/useMessage';
import { Boot } from "@wangeditor/editor";
import mdModule from "@wangeditor/plugin-md";

// 注册 md 插件，只执行一次
Boot.registerModule(mdModule);

interface EditorProps {
  value: string;
  onChange: (html: string) => void;
}

function ArticleEditor({ value, onChange }: EditorProps) {
  const message = useMessage();
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  const isInitializingRef = useRef(true);
  const lastValueRef = useRef<string>("");
// 使用默认配置即可，不要修改此配置
  const toolbarConfig: Partial<IToolbarConfig> = {};

const editorConfig: Partial<IEditorConfig> = {
    placeholder: "请输入内容...",
    MENU_CONF: {
      md: {}, // 启用 md 菜单
      fontSize: {
        fontSizeList: ['12px', '13px', '14px', '15px', '16px', '17px', '18px', '19px', '20px', '22px', '24px', '28px', '32px', '36px', '48px', '72px']
      },
      uploadImage: {
        async customUpload(file: File, insertFn: (url: string, alt?: string, href?: string) => void) {
          try {
            const res = await ossAPI.getSign();
            if (!res.success) {
              message.error("获取上传签名失败");
              return;
            }

            const { accessKeyId, policy, signature, dir, host } = res.data;
            const key = `${dir}images/${Date.now()}-${file.name}`;

            const formData = new FormData();
            formData.append("key", key);
            formData.append("policy", policy);
            formData.append("OSSAccessKeyId", accessKeyId);
            formData.append("success_action_status", "200");
            formData.append("signature", signature);
            formData.append("file", file);

            const uploadRes = await fetch(host, {
              method: "POST",
              body: formData,
            });

            if (uploadRes.ok) {
              const imageUrl = `${host}/${key}`;
              insertFn(imageUrl, file.name);
              message.success("图片上传成功");
            } else {
              message.error("上传失败");
              throw new Error("上传失败");
            }
          } catch (error) {
            console.error("上传图片失败:", error);
            message.error("上传图片失败");
          }
        },
      },
      uploadVideo: {
        async customUpload(file: File, insertFn: (url: string, poster?: string) => void) {
          try {
            // 检查文件类型
            const allowedTypes = ['video/mp4', 'video/webm', 'video/ogg', 'video/avi', 'video/mov'];
            if (!allowedTypes.includes(file.type)) {
              message.error("只支持 MP4、WebM、OGG、AVI、MOV 格式的视频文件");
              return;
            }

            // 检查文件大小 (限制为100MB)
            const maxSize = 1000 * 1024 * 1024; // 100MB
            if (file.size > maxSize) {
              message.error("视频文件大小不能超过1000MB");
              return;
            }

            const res = await ossAPI.getSign();
            if (!res.success) {
              message.error("获取上传签名失败");
              return;
            }

            const { accessKeyId, policy, signature, dir, host } = res.data;
            const key = `${dir}videos/${Date.now()}-${file.name}`;

            const formData = new FormData();
            formData.append("key", key);
            formData.append("policy", policy);
            formData.append("OSSAccessKeyId", accessKeyId);
            formData.append("success_action_status", "200");
            formData.append("signature", signature);
            formData.append("file", file);

            const uploadRes = await fetch(host, {
              method: "POST",
              body: formData,
            });

            if (uploadRes.ok) {
              const videoUrl = `${host}/${key}`;
              insertFn(videoUrl);
              message.success("视频上传成功");
            } else {
              message.error("上传失败");
              throw new Error("上传失败");
            }
          } catch (error) {
            console.error("上传视频失败:", error);
            message.error("上传视频失败");
          }
        },
      },
    },
  };

  // 当外部 value 变化且与编辑器内容不一致时，主动同步到编辑器，避免首次加载竞态导致内容丢失
  useEffect(() => {
    if (!editor) return;
    const currentHtml = editor.getHtml();
    if (value != null && value !== currentHtml) {
      editor.setHtml(value || "");
    }
    lastValueRef.current = value || "";
  }, [value, editor]);

  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  return (
    <div style={{ border: "1px solid #ccc", zIndex: 100 }}>
      <Toolbar editor={editor} defaultConfig={toolbarConfig} mode='default' style={{ borderBottom: "1px solid #ccc" }} />
      <Editor
        defaultConfig={editorConfig}
        value={value}
        onCreated={(ed) => {
          setEditor(ed);
          // 确保创建时立即呈现外部传入的内容
          if (value != null) {
            ed.setHtml(value || "");
            lastValueRef.current = value || "";
          }
          // 初始化阶段，忽略编辑器触发的首次 onChange（通常为空内容），避免覆盖后台返回的内容
          // 在下一事件循环标记初始化完成
          Promise.resolve().then(() => {
            isInitializingRef.current = false;
          });
        }}
        onChange={(ed) => {
          const html = ed.getHtml();
          if (isInitializingRef.current) return;
          // 仅在内容真实变化时向外抛出，避免无意义的回写
          if (html !== lastValueRef.current) {
            lastValueRef.current = html;
            onChange(html);
          }
        }}
        mode='default'
        style={{ height: "500px", overflowY: "hidden" }}
      />
    </div>
  );
}

export default ArticleEditor;
